package com.lihh.rocket5.normal;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeOrderlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeOrderlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerOrderly;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.remoting.common.RemotingHelper;

import java.io.UnsupportedEncodingException;
import java.util.List;

public class SingleQueueConsumer {
  public static void main(String[] args) throws MQClientException {
    // 实例化 消费者实例
    DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("consumer_group_001");
    // 设置 name server
    consumer.setNamesrvAddr("localhost:9876");
    // 订阅主题
    consumer.subscribe("order004", "*");
    // 设置消费的 偏移量
    consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
    
    // 注册 消费的事件
    consumer.registerMessageListener(new MessageListenerOrderly() {
      @Override
      public ConsumeOrderlyStatus consumeMessage(List<MessageExt> list, ConsumeOrderlyContext consumeOrderlyContext) {
        for (MessageExt messageExt : list) {
          String topic = messageExt.getTopic();
          String msgId = messageExt.getMsgId();
          try {
            String message = new String(messageExt.getBody(), RemotingHelper.DEFAULT_CHARSET);
            
            System.out.println(String.format("主题: %s, 消息id: %s, 消息体: %s", topic, msgId, message));
          } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
          }
          
        }
        return ConsumeOrderlyStatus.SUCCESS;
      }
    });
    
    consumer.start();
    while (true) {
    }
  }
}
